/*
 * @Author: zhaoxm
 * @Date: 2022-02-24 13:37:45
 * @LastEditTime: 2022-09-02 12:34:03
 * @Description: 用于取消axios 重复请求
 */

import axios from "axios"
import _ from "lodash"

export const getPendingUrl = (config) => [config.method, config.url].join("&")

class AxiosCanceler {
  pendingMap = new Map()

  static instance = null

  static getInstance() {
    return AxiosCanceler.instance
  }

  /**
   * @description: 添加请求
   * @param { Object } config
   */
  addPending(config) {
    this.removePending(config)
    const url = getPendingUrl(config)

    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!this.pendingMap.has(url)) this.pendingMap.set(url, cancel)
      })
  }

  removeAllPending() {
    for (const cancel of this.pendingMap) {
      cancel && _.isFunction(cancel) && cancel()
    }
    this.pendingMap.clear()
  }

  /**
   * @description: 删除指定请求
   * @param { Object } config
   */
  removePending(config) {
    const url = getPendingUrl(config)

    if (this.pendingMap.has(url)) {
      const cancel = this.pendingMap.get(url)
      cancel && cancel(url)
      this.pendingMap.delete(url)
    }
  }

  reset() {
    this.pendingMap = new Map()
  }
}

export function getAxiosCanceler() {
  const instance = AxiosCanceler.getInstance()
  if (instance) return instance
  AxiosCanceler.instance = new AxiosCanceler()
  return AxiosCanceler.instance
}
